package com.zhixinhuixue.zsyte.xxx.ui.activity

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.inputmethod.EditorInfo
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.scandecode.ScanDecode
import com.scandecode.inf.ScanInterface
import com.scandecode.inf.ScanInterface.OnScanListener
import com.zhixinhuixue.library.common.ext.dp
import com.zhixinhuixue.zsyte.xxx.R
import com.zhixinhuixue.zsyte.xxx.app.api.NetUrl
import com.zhixinhuixue.zsyte.xxx.app.base.BaseActivity
import com.zhixinhuixue.zsyte.xxx.app.ext.initBack
import com.zhixinhuixue.zsyte.xxx.databinding.ActivityWlckBinding
import com.zhixinhuixue.zsyte.xxx.ui.adapter.WLPBAdapter
import com.zhixinhuixue.zsyte.xxx.ui.viewmodel.WLCKViewModel
import me.hgj.mvvmhelper.ext.*
import me.hgj.mvvmhelper.net.LoadStatusEntity
import me.hgj.mvvmhelper.net.LoadingDialogEntity
import me.hgj.mvvmhelper.util.decoration.DividerOrientation
import java.util.*


/**
 * 作者　: hegaojian
 * 时间　: 2020/11/18
 * 描述　: 虽然在Activity代码少了，但是DataBinding 不太好用
 */
class WLCKActivity : BaseActivity<WLCKViewModel, ActivityWlckBinding>() {
    private var mRelationship: MutableList<String> = ArrayList()
    private var mDeliveryLabelsItems: MutableList<String> = ArrayList()
    private var mNames: MutableList<String> = ArrayList()
    private var scanDecode: ScanInterface? = null
    private val mAdapter: WLPBAdapter by lazy { WLPBAdapter() }

    override fun initView(savedInstanceState: Bundle?) {
        //初始化toolbar
        mToolbar.initBack("物料出库") {
            finish()
        }
        mDataBind.viewModel = mViewModel
        mDataBind.click = LoginClickProxy()
        mViewModel.getStoresRequisitionSheet()

        //初始化recyclerview
        mDataBind.listRecyclerView.run {
            vertical()
            divider {
                setColor(getColorExt(R.color.colorDivider))
                setDivider(1.dp)
                includeVisible = false
                orientation = DividerOrientation.VERTICAL
            }
            adapter = mAdapter
        }

        mDataBind.edtWlpb.setOnEditorActionListener { view, actionId, keyEvent ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                if (!TextUtils.isEmpty(mDataBind.edtWlpb.text.toString())) {
                    mAdapter.addData(mDataBind.edtWlpb.text.toString())
                    mDataBind.edtWlpb.setText("")
                    mDataBind.edtWlpb.clearFocus()
                    mDataBind.edtWlpb.requestFocus()
                } else {
                    "请输入数据".toast()
                }
                true
            }
            false
        }

        initScanner()
    }

    private fun initScanner() {
        try {
            scanDecode = ScanDecode(this)
            scanDecode?.initService("true")
            scanDecode?.getBarCode(object : OnScanListener {
                override fun getBarcode(data: String) {
                    if (!TextUtils.isEmpty(data)) {
                        mDataBind.edtWlpb.setText(data)
                        mDataBind.edtWlpb.clearFocus()
                        mDataBind.edtWlpb.requestFocus()
                        mAdapter.addData(data)
                    } else {

                    }
                }

                override fun getBarcodeByte(bytes: ByteArray) {}
            })
        } catch (e: Exception) {

        }


    }


    /**
     * 请求成功
     */
    override fun onRequestSuccess() {
        //监听登录结果
        mViewModel.sheetData.observe(this, {
            it.forEach { item ->
                mRelationship.add(item.Code)
            }
        })


        mViewModel.itemData.observe(this, {
            mNames.clear()
            it.forEach { item ->
                mNames.add(item.Material_Name)
            }
        })


        mViewModel.commitData.observe(this, {
            runOnUiThread {
                "操作成功".toast()
                mDataBind.edtJwh.text = ""
                mDataBind.edtLpb.text = ""
                mDataBind.edtWlpb.setText("")
                mDataBind.edtJwh.tag = null
                mDataBind.edtLpb.tag = null
                mDataBind.edtWlpb.clearFocus()
                mAdapter.data.clear()
                mAdapter.notifyDataSetChanged()
            }
        })


    }

    /**
     * 请求失败
     * @param loadStatus LoadStatusEntity
     */
    override fun onRequestError(loadStatus: LoadStatusEntity) {
        when (loadStatus.requestCode) {
            NetUrl.GET_STORESREQUISITIONSHEET -> {
                showDialogMessage(loadStatus.errorMessage)
            }

            NetUrl.GET_STORESREQUISITIONSHEET_ITEM -> {
                showDialogMessage(loadStatus.errorMessage)
            }

            NetUrl.Picking -> {
                showDialogMessage(loadStatus.errorMessage)
            }
        }
    }

    inner class LoginClickProxy {

    }

    override fun showCustomLoading(setting: LoadingDialogEntity) {
        if (setting.requestCode == NetUrl.LOGIN) {
            //可以根据不同的code 做不同的loading处理
            showLoadingUi()
        }
    }

    override fun dismissCustomLoading(setting: LoadingDialogEntity) {
        if (setting.requestCode == NetUrl.LOGIN) {
            //可以根据不同的code 做不同的loading处理
            showSuccessUi()
        }
    }

    override fun onDestroy() {

        try {
            scanDecode!!.stopScan()
            scanDecode!!.onDestroy()

        } catch (e: Exception) {

        }
        super.onDestroy()
    }

    private fun initNoLinkOptionsPicker() { // 不联动的多级选项
        val pvNoLinkOptions =
            OptionsPickerBuilder(
                this
            ) { options1, options2, options3, v ->
                mDataBind.edtJwh.setText(
                    mRelationship.get(options1)
                )
                mDataBind.edtJwh.tag = mViewModel.sheetData.value!![options1].Id
                mViewModel.getStoresRequisitionSheetById(mViewModel.sheetData.value!![options1].Id)
            }
                .setOptionsSelectChangeListener { options1, options2, options3 -> }
                .setItemVisibleCount(5)
                .setSubmitText("确定") //确定按钮文字
                .setCancelText("取消") //取消按钮文字
                .setSubCalSize(18) //确定和取消文字大小
                .setTitleSize(20) //标题文字大小
                .setLineSpacingMultiplier(3f)
                .setTitleColor(Color.BLACK) //标题文字颜色
                .setSubmitColor(-0xc17c07) //确定按钮文字颜色
                .setCancelColor(-0x838282) //取消按钮文字颜色
                .setTitleBgColor(Color.WHITE) //标题背景颜色 Night mode
                .setBgColor(Color.WHITE) //滚轮背景颜色 Night mode
                .setContentTextSize(18) //滚轮文字大小
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label
                .build<Any>()
        pvNoLinkOptions.setPicker(mRelationship as List<Any>?)
        pvNoLinkOptions.setSelectOptions(0, 1, 1)
        pvNoLinkOptions.show()
    }


    private fun initNoLinkOptionsPicker2() { // 不联动的多级选项
        val pvNoLinkOptions =
            OptionsPickerBuilder(
                this
            ) { options1, options2, options3, v ->
                mDataBind.edtLpb.setText(
                    mNames.get(options1)
                )
                mDataBind.edtLpb.tag = mViewModel.itemData.value!![options1].Material_Id
                mDataBind.edtWlpb.requestFocus()
            }
                .setOptionsSelectChangeListener { options1, options2, options3 -> }
                .setItemVisibleCount(5)
                .setSubmitText("确定") //确定按钮文字
                .setCancelText("取消") //取消按钮文字
                .setSubCalSize(18) //确定和取消文字大小
                .setTitleSize(20) //标题文字大小
                .setLineSpacingMultiplier(3f)
                .setTitleColor(Color.BLACK) //标题文字颜色
                .setSubmitColor(-0xc17c07) //确定按钮文字颜色
                .setCancelColor(-0x838282) //取消按钮文字颜色
                .setTitleBgColor(Color.WHITE) //标题背景颜色 Night mode
                .setBgColor(Color.WHITE) //滚轮背景颜色 Night mode
                .setContentTextSize(18) //滚轮文字大小
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label
                .build<Any>()
        pvNoLinkOptions.setPicker(mNames as List<Any>?)
        pvNoLinkOptions.setSelectOptions(0, 1, 1)
        pvNoLinkOptions.show()
    }


    override fun onBindViewClick() {
        setOnclickNoRepeat(mDataBind.edtJwh, mDataBind.edtLpb, mDataBind.tvLogin) {
            when (it.id) {
                R.id.edt_jwh -> {
                    initNoLinkOptionsPicker()
                }
                R.id.edt_lpb -> {
                    if (! mNames.isNullOrEmpty()) {
                        initNoLinkOptionsPicker2()
                    } else {
                        "请先选择物料领用单".toast()
                    }

                }

                R.id.tv_login -> {
                    when {
                        mDataBind.edtJwh.text.toString().isEmpty() -> "请选择物料领用单".toast()
                        mDataBind.edtLpb.text.toString().isEmpty() -> "请选择物料名称".toast()
                        mAdapter.data.isNullOrEmpty() -> "请输入物料盘标".toast()
                        else -> {
                            mViewModel.Picking(
                                mDataBind.edtJwh.tag as String,
                                mDataBind.edtLpb.tag as String,
                                mAdapter.data
                            )
                        }
                    }
                }

            }
        }
    }


}